import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/diagnostics.dart';
import 'package:yt_devops/components/app_permission/yt_tab_view_model.dart';
import 'package:yt_devops/utils/func_utils.dart';

class AuthTab extends StatefulWidget {
  final int currnentIndex;
  final Widget Function(
    BuildContext context,
    List<YtTabViewModel> filtes,
    TabController tabController,
  ) build;

  List<YtTabViewModel> _filteList = [];

  AuthTab(
      {required List<YtTabViewModel> tabList,
      required this.build,
      int? currnentTabIndex,
      super.key})
      : currnentIndex = currnentTabIndex ?? 0,
        _filteList = tabList
            .where((element) =>
                FuncUtils.isPassAuthority([element.permissionString]))
            .toList();

  @override
  State<AuthTab> createState() => _AuthTabState();
}

class _AuthTabState extends State<AuthTab> with TickerProviderStateMixin {
  late TabController _tabController;

  // late AuthTabData tabData;

  late int _tabsHash;

  @override
  void initState() {
    _tabController = TabController(
        length: widget._filteList.length,
        vsync: this,
        initialIndex: widget.currnentIndex);
    var activeIndex = _tabController.index;
    _tabsHash = activeIndex < widget._filteList.length
        ? widget._filteList[activeIndex].hashCode
        : Random(1000).hashCode;
    super.initState();
    _tabController.addListener(() {
      var activeIndex = _tabController.index;
      _tabsHash = activeIndex < widget._filteList.length
          ? widget._filteList[activeIndex].hashCode
          : Random(1000).hashCode;
      setState(() {});
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AuthTabWidget(
      data: _tabController,
      child: Builder(
        key: ValueKey(_tabsHash),
        builder: (context) =>
            widget.build(context, widget._filteList, _tabController),
      ),
    );
    // _.dependOnInheritedWidgetOfExactType.ac
  }
}

class AuthTabWidget extends InheritedWidget {
  final TabController data;

  const AuthTabWidget({Key? key, required this.data, required Widget child})
      : super(key: key, child: child);

  static AuthTabWidget of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<AuthTabWidget>()!;
  }

  @override
  bool updateShouldNotify(AuthTabWidget oldWidget) {
    return true;
  }
}
